var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
var cors = require("cors");
var fs = require("fs");

// Initialize MongoDB connection
require("./db/index");
require("dotenv").config();

var indexRouter = require("./routes/index");

var usersRouter = require("./routes/users");
var jjxRouter = require("./routes/jjx");
var {
  router: cosmeticRouter,
  setupProvinceSocketIO,
} = require("./routes/cosmetic");
var meticalRouter = require("./routes/metical");
var authRouter = require("./routes/jjxtwo");
var aiimgRouter = require("./routes/aiimg");
var pccosmeticRouter = require("./routes/pccosmetic");
var pcproductimgRouter = require("./routes/pcproductimg");
var pcorganizationRouter = require("./routes/pcorganization");
var pcdoctorRouter = require("./routes/pcdoctor");
var aisaveRouter = require("./routes/aisave");
// var authRouter = require('./routes/auth');
var trtcRouter = require("./routes/trtc");
var passwordSecurityRouter = require("./routes/passwordSecurity");

var app = express();

app.use(cors()); // 解决跨域问题
// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");

app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
// 静态托管上传目录，供音频等资源访问
const uploadsDir = path.join(__dirname, "uploads");
try {
  if (!fs.existsSync(uploadsDir)) fs.mkdirSync(uploadsDir, { recursive: true });
} catch (_) {}
app.use("/uploads", express.static(uploadsDir));

app.use("/uploads", express.static(path.join(__dirname, "public/uploads")));
app.use("/", indexRouter);
app.use("/users", usersRouter);
app.use("/metical", meticalRouter);
app.use("/auth", authRouter);
app.use("/cosmetic", cosmeticRouter);
app.use("/jjx", jjxRouter);
// app.use("/api/auth", authRouter);
app.use("/aiimg", aiimgRouter);
app.use("/pccosmetic", pccosmeticRouter);
app.use("/pcproductimg", pcproductimgRouter);
app.use("/pcorganization", pcorganizationRouter);
app.use("/pcdoctor", pcdoctorRouter);
app.use("/api/auth", authRouter);
app.use("/aisave", aisaveRouter);
app.use("/api", trtcRouter);
app.use("/api/security", passwordSecurityRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

module.exports = app;
